package com.xm.xmapp.http;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.ThreadPoolFactory;
import com.xm.xmapp.tool.AndroidTool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdataAppClass {

	public ProgressDialog pBar;
	public Handler handler1;
	public HandlerInterFace in;
	private static UpdataAppClass up;
	private boolean isQuxiao;
	/**
	 * 更新apk文件名字
	 */
	public static String APK_NAME = "";
	public interface HandlerInterFace {
		public void run(Message msg);
	}

	public synchronized boolean isQuxiao() {
		return isQuxiao;
	}

	public synchronized void setQuxiao(boolean isQuxiao) {
		this.isQuxiao = isQuxiao;
	}

	private UpdataAppClass() {
	}

	public synchronized static UpdataAppClass getUpdataAppClass() {
		if (up == null)
			up = new UpdataAppClass();
		return up;
	}

	@SuppressWarnings("deprecation")
	public void downFile(final String url, final Activity activity, HandlerInterFace in) {

		this.in = in;
		pBar = new ProgressDialog(activity, ProgressDialog.THEME_HOLO_LIGHT); // 进度条，在下载的时候实时更新进度，提高用户友好度
		pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// R.style.Dialog
		pBar.setTitle("正在下载");
		pBar.setMessage("请稍候...");
		pBar.setProgress(0);
		pBar.setCancelable(false);
		setQuxiao(false);
		pBar.setButton(DialogInterface.BUTTON_POSITIVE, "取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				setQuxiao(true);
			}
		});

		pBar.show();
		handler1 = new Handler();
		ThreadPoolFactory.getInstance().execute(new Runnable() {

			@Override
			public void run() {

				deleteAllFiles(MyAppcation.getMyAppcation().getExternalFilesDir("myapk"));
				File file = new File(MyAppcation.getMyAppcation().getExternalFilesDir("myapk") + "/", APK_NAME
						+ ".temp");
				try {
					HttpURLConnection urlcon = (HttpURLConnection) new URL(url).openConnection();
					int length = (int) urlcon.getContentLength(); // 获取文件大小
					if (length > 0) {
						pBar.setMax(length); // 设置进度条的总长度
						InputStream is = urlcon.getInputStream();
						FileOutputStream fileOutputStream = null;
						if (is != null) {
							fileOutputStream = new FileOutputStream(file);
							// 这个是缓冲区，即一次读取10个比特，我弄的小了点，因为在本地，所以数值太大一下就下载完了,
							// 看不出progressbar的效果。
							byte[] buf = new byte[1024];
							int ch = -1;
							int process = 0;
							while ((ch = is.read(buf)) != -1) {
								if (!isQuxiao()) {
									fileOutputStream.write(buf, 0, ch);
									process += ch;
									pBar.setProgress(process); // 这里就是关键的实时更新进度了！
									float max = length;
									float all = max / 1024 / 1024;
									float downLength = process;
									float percent = downLength / 1024 / 1024;
									pBar.setProgressNumberFormat(String.format("%.2fM/%.2fM", percent, all));
								} else {
									if (file != null && file.isFile()) {
										file.delete();
									}
									break;
								}
							}
						}
						if (!isQuxiao()) {
							fileOutputStream.flush();
							if (fileOutputStream != null) {
								fileOutputStream.close();
							}
							if (file != null && file.isFile()) {
								file.renameTo(new File(MyAppcation.getMyAppcation().getExternalFilesDir("myapk") + "/",
										APK_NAME + ".apk"));
							}
							down();
						} else {
							handler1.post(new Runnable() {
								public void run() {
									pBar.cancel();
									activity.finish();
								}
							});
						}
					} else {
						handler1.post(new Runnable() {
							public void run() {
								pBar.cancel();
								AndroidTool.showMessage("解析包出错，请联系客服!");
							}
						});
					}
				} catch (Exception e) {
					if (file != null && file.isFile()) {
						file.delete();
					}
				}
			}
		});
	}

	public static void deleteAllFiles(File root) {
		File files[] = root.listFiles();
		if (files != null)
			for (File f : files) {
				if (f.isDirectory()) { // 判断是否为文件夹
					deleteAllFiles(f);
					try {
						f.delete();
					} catch (Exception e) {
					}
				} else {
					if (f.exists()) { // 判断是否存在
						deleteAllFiles(f);
						try {
							f.delete();
						} catch (Exception e) {
						}
					}
				}
			}
	}

	public void down() {
		handler1.post(new Runnable() {
			public void run() {
				pBar.cancel();
				update();
			}
		});
	}

	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(
				Uri.fromFile(new File(MyAppcation.getMyAppcation().getExternalFilesDir("myapk") + "/", APK_NAME
						+ ".apk")), "application/vnd.android.package-archive");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		MyAppcation.getMyAppcation().startActivity(intent);
		if (in != null)
			in.run(null);
	}
}
